import React, { Component, Fragment } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Upload, Button, message } from 'antd';
import { connect } from 'dva';
import Authorized from '@/utils/Authorized';
import { requestHeadersMd5 } from '@/utils/utils';
import Img from '@/assets/defaultImg.png';
import styles from './BaseView.less';

const FormItem = Form.Item;

@connect(({ personalset, loading }) => ({
  infoList: personalset.infoList,
  editSwitch: personalset.editSwitch,
  loading: loading.models.personalset,
}))
@Form.create()
class BaseView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      imageUrl: '',
      userPortrait: '',
      editSwitch: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'personalset/fetchUserInfo', // 回显
      payload: {},
      callback: res => {
        this.setState({ userPortrait: res.userPortrait });
      },
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'personalset/editMessage', // 点击修改
      payload: {},
    });
  }

  getAvatarURL() {
    const { infoList } = this.props;
    if (infoList.userPortrait) {
      const fileId = infoList.userPortrait;
      return `/mgrApi/fileServer/showImage?fileId=${fileId}`; // 后台返回
    }
    const url = Img; // 默认的
    return url;
  }

  getViewDom = ref => {
    this.view = ref;
  };

  handleChange = info => {
    if (info.file.status === 'done') {
      if (info.file.response.success) {
        const urlId = info.file.response.data.split('|')[0];
        this.setState({
          imageUrl: `/mgrApi/fileServer/showImage?fileId=${urlId}`,
          userPortrait: urlId,
        });
        message.success(info.file.response.message || '上传成功');
      } else {
        message.error('上传失败');
      }
    }
  };

  beforeUpload = file => {
    const isJPG = file.type === 'image/jpeg';
    if (!isJPG) {
      message.error('请上传jpg格式的图片!');
    }
    return isJPG;
  };

  edit = e => {
    this.setState({
      editSwitch: e,
    });
  };

  // 更新数据
  updateInfo = () => {
    const { dispatch, form } = this.props;
    const { userPortrait } = this.state;
    form.validateFieldsAndScroll((err, valuse) => {
      if (!err) {
        dispatch({
          type: 'personalset/updateUserBaseInfo', // 更新
          payload: {
            ...valuse,
            userPortrait,
          },
          callback: response => {
            if (response.success) {
              message.success(response.message || '更新成功！');
              this.setState({
                editSwitch: false,
              });
              dispatch({
                type: 'personalset/fetchUserInfo', // 回显
                payload: {},
                callback: res => {
                  dispatch({
                    type: 'login/updateUserName', // 更新用户名
                    payload: {
                      userName: res.userName,
                      userPortrait: res.userPortrait,
                    },
                  });
                },
              });
            } else {
              message.error(response.message || '更新失败！');
              dispatch({
                type: 'personalset/editMessage', // 点击修改
                payload: { edited: false },
              });
            }
          },
        });
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      infoList,
    } = this.props;
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const formItemLayouts = {
      labelCol: { md: { span: 8 } },
      wrapperCol: { md: { span: 16 } },
    };

    const formItemLayoutone = {
      labelCol: { md: { span: 8 } },
      wrapperCol: { md: { span: 16 } },
    };

    const { editSwitch, imageUrl } = this.state;
    const AvatarView = ({ avatar }) => (
      <Fragment>
        <Upload
          beforeUpload={this.beforeUpload}
          action="/mgrApi/fileServer/uploadFile"
          headers={requestHeadersMd5()}
          onChange={this.handleChange}
        >
          <div className={styles.avatar_title}>头像</div>
          <div className={styles.avatar} style={{ borderRadius: '50%' }}>
            <img src={imageUrl || avatar} alt="avatar" style={{ height: '100%' }} />
          </div>
          {editSwitch ? (
            <div className={styles.button_view}>
              <Authorized authority="business:basicInformation:updateUserBaseInfo" noMatch={null}>
                <Button icon={<UploadOutlined />}>更换头像</Button>
              </Authorized>
            </div>
          ) : null}
        </Upload>
      </Fragment>
    );
    return (
      <div className={styles.baseView} ref={this.getViewDom}>
        <div className={styles.left} style={{ width: '350px' }}>
          <Form layout="vertical" onSubmit={this.handleSubmit}>
            <FormItem label="所属公司：" {...formItemLayoutone} style={{ margin: '40px 0 0 0' }}>
              <span>{infoList.corpName}</span>
            </FormItem>
            <div style={{ clear: 'both' }} />
            <FormItem label="所属部门：" {...formItemLayoutone} style={{ margin: '40px 0 0 0' }}>
              <span>{infoList.orgName}</span>
            </FormItem>

            <div style={{ clear: 'both' }} />
            <div style={{ margin: '40px 0 0 0' }}>
              {editSwitch ? (
                <FormItem label="用户名：" {...formItemLayout}>
                  {getFieldDecorator('userName', {
                    rules: [{ required: true, message: '请输入' }],
                    initialValue: infoList.userName,
                  })(<Input placeholder="请输入" maxLength={16} />)}
                </FormItem>
              ) : (
                <FormItem label="用户名：" {...formItemLayouts}>
                  {getFieldDecorator('userName', {
                    rules: [{ required: true, message: '请输入' }],
                    initialValue: infoList.userName,
                  })(<span>{infoList.userName}</span>)}
                </FormItem>
              )}
            </div>

            <div>
              {editSwitch ? (
                <FormItem label="联系电话：" {...formItemLayout}>
                  {getFieldDecorator('mobile', {
                    rules: [
                      {
                        required: true,
                        message: '固话或手机',
                        pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                      },
                    ],
                    initialValue: infoList.mobile,
                  })(<Input placeholder="请输入" maxLength={12} />)}
                </FormItem>
              ) : (
                <FormItem label="联系电话：" {...formItemLayouts}>
                  {getFieldDecorator('mobile', {
                    rules: [
                      {
                        required: true,
                        message: '固话或手机',
                        pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                      },
                    ],
                    initialValue: infoList.mobile,
                  })(<span>{infoList.mobile}</span>)}
                </FormItem>
              )}
            </div>

            <div>
              {editSwitch ? (
                <FormItem label="邮箱：" {...formItemLayout}>
                  {getFieldDecorator('email', {
                    rules: [{ required: true, type: 'email', message: '应为邮箱格式' }],
                    initialValue: infoList.email,
                  })(<Input placeholder="请输入" maxLength={30} />)}
                </FormItem>
              ) : (
                <FormItem label="邮箱：" {...formItemLayouts}>
                  {getFieldDecorator('email', {
                    rules: [{ required: true, type: 'email', message: '应为邮箱格式' }],
                    initialValue: infoList.email,
                  })(<span>{infoList.email}</span>)}
                </FormItem>
              )}
            </div>
            <Authorized authority="business:basicInformation:updateUserBaseInfo" noMatch={null}>
              {!editSwitch ? (
                <Button type="primary" onClick={() => this.edit(true)}>
                  修改
                </Button>
              ) : (
                <Button type="primary" onClick={this.updateInfo}>
                  保存
                </Button>
              )}
            </Authorized>
          </Form>
        </div>
        <div className={styles.right}>
          <AvatarView avatar={this.getAvatarURL()} />
        </div>
      </div>
    );
  }
}

export default BaseView;
